package it.univaq.mwt.business.impl;

import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.Remote;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import it.univaq.mwt.business.AlbumFotograficoService;
import it.univaq.mwt.business.model.AlbumFotografico;
import it.univaq.mwt.business.model.Canzone;
import it.univaq.mwt.business.model.Foto;






@Stateless
@Remote(AlbumFotograficoService.class)
public class EJBAlbumFotografico implements AlbumFotograficoService {
	
	@PersistenceContext
	private EntityManager em;

	@Resource
	private SessionContext etx;
	
	public EJBAlbumFotografico() {
		super();
		// TODO Auto-generated constructor stub
	}
	//transazione
	public List<AlbumFotografico> getAllPhotoAlbumsByGroupId(int groupID){
		
		Query query = em.createQuery("SELECT alb FROM AlbumFotografico alb, Gruppo g WHERE g.id=:groupID AND  alb.utente.id = g.id");
		query.setParameter("groupID", groupID);
		
		List<AlbumFotografico> albums = (List<AlbumFotografico>)query.getResultList();
		Iterator<AlbumFotografico> i = albums.iterator();
		em.flush();
		
		return albums;
		
	}
	
	@Override
	public Foto getFotoProfiloByGroupId(int groupID) {
		Query query = em.createQuery("SELECT f FROM  Foto f, AlbumFotografico alb, Gruppo g WHERE g.id=:groupID AND alb.utente.id = g.id AND alb.tag=:profile");
		query.setParameter("groupID", groupID);
		String profile = "profile";
		query.setParameter("profile", profile);
		Foto result = (Foto)query.getSingleResult();
		return result;
	}

	public void addPhotoAlbum(AlbumFotografico album){
		AlbumFotografico albumToAdd = new AlbumFotografico();
		albumToAdd = album;
		em.persist(albumToAdd);
		
	}
	
	public AlbumFotografico updatePhotoAlbum(AlbumFotografico album){
		AlbumFotografico a = em.merge(album);;
		return a;
	}

	//@Transactional
	public AlbumFotografico insertAlbumFotografico(AlbumFotografico album) {
		AlbumFotografico a = album;
		em.persist(a);
		return a;
	}
	@Override
	public int emptyAlbumFotografico(AlbumFotografico album) {
		Query query = em.createQuery("SELECT COUNT(alb) FROM AlbumFotografico alb WHERE alb.utente.id=:albumID");
		query.setParameter("albumID", album.getUtente().getId());
		
		Long i = (Long) query.getSingleResult();
		return i.intValue();
	}
	//@Transactional
	public void removeAlbumFotografico(AlbumFotografico album) {
		Query query = em.createQuery("delete from AlbumFotografico f where f.id =:albumID");
		query.setParameter("albumID", album.getId());
		query.executeUpdate();
		em.getEntityManagerFactory().getCache().evict(AlbumFotografico.class);
		
	}

}
